package net.koodar.forge.common.utils;

import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * bean相关工具类
 *
 * @author liyc
 */
public class BeanUtil {

	/**
	 * 复制对象
	 *
	 * @param source 源 要复制的对象
	 * @param target 目标 复制到此对象
	 */
	public static <T> T copy(Object source, Class<T> target) {
		if (source == null || target == null) {
			return null;
		}
		try {
			T newInstance = target.newInstance();
			BeanUtils.copyProperties(source, newInstance);
			return newInstance;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 复制对象
	 *
	 * @param source 源 要复制的对象
	 * @param target 目标 复制到此对象
	 */
	public static <T> T copy(Object source, T target) {
		if (source == null || target == null) {
			return null;
		}
		try {
			BeanUtils.copyProperties(source, target);
			return target;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	/**
	 * 复制对象
	 *
	 * @param source 源 要复制的对象
	 * @param target 目标 复制到此对象
	 * @param ignoreProperties 忽略的字段
	 */
	public static <T> T copy(Object source, T target, String... ignoreProperties) {
		if (source == null || target == null) {
			return null;
		}
		try {
			BeanUtils.copyProperties(source, target, ignoreProperties);
			return target;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 复制集合
	 * @param source 源 要复制的对象
	 * @param target 目标 复制到此对象
	 */
	public static <S, T> List<T> copy(List<S> source, Class<T> target) {
		if (source == null || target == null) {
			return null;
		}
		try {
			return source.stream().map(s -> copy(s, target)).collect(Collectors.toList());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
